package com.example.jack.community.view.home.homeAdapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.jack.community.R;
import com.example.jack.community.common.utils.CustomImageView;
import com.example.jack.community.data.HomeRcViewpagerBean;

import java.util.ArrayList;

/**
 * Created by vveng on 2017/11/30 11: 29
 *
 * @mail: vvengStruggle@163.com
 */

public class HomeViewpagerAdapter2 extends PagerAdapter {
    private Context mContext;
    private ArrayList<HomeRcViewpagerBean> mbeans;
    private CustomImageView mImage;

    public HomeViewpagerAdapter2(Context context, ArrayList<HomeRcViewpagerBean> mRcViewpagerBeen) {
        mContext = context;
        mbeans = mRcViewpagerBeen;
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE; //为了能循环
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        position = position % mbeans.size();
        if (position < 0) {//如果是第一张图片，向左滑动会出现position负数的情况
            position = mbeans.size() + position; //这里把它指向最后一张图片
        }
        //使用自定义弧形图片
        mImage = new CustomImageView(mContext);
       // ImageView mImage = new ImageView(mContext);
        RequestOptions options = new RequestOptions()
                .error(R.mipmap.ic_launcher)
                .centerCrop();
         Glide.with(mContext)
                .asBitmap()
                .load(mbeans.get(position).getImageUrl())
                 .apply(options)
                .into(mImage);

        //这里要加上removeView否则可能报错
        // The specified child already has a parent. You must call removeView() on the child's parent first异常
        //经过查阅得到一个通俗易懂的解释：从字面意思上是说这个特定的child已经有一个parent了，
        // 你必须在这个parent中首先调用removeView()方法，才能继续你的内容。这里很明显这个child是一个View，
        // 一个子（child）View必须依赖于父（parent）View，如果你要使用这个child，则必须通过parent，
        // 而你如果就是硬想使用这个child，那么就得让这个child与parent脱离父子关系（即removeView（））
        ViewParent viewParent = mImage.getParent();
        if (viewParent != null) {
            ViewGroup parent = (ViewGroup) viewParent;
            parent.removeView(mImage);
        }
        container.addView(mImage); //将图片放入viewpager
        return mImage;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    }
    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
}
